package test;

import static org.junit.Assert.*;

import model.Email;
import model.EmailApplicationModel;
import model.Filter;
import model.EmailImp;
import model.EmailApplicationModelImp;
import model.MeetingMail;
import model.User;
import model.Template;
import network.NetworkServerClientRequestHandler;
import requestManager.EmailApplicationRequestManager;
import requestManager.EmailApplicationRequestManagerImp;
import resources.ResourceProvider;
import simulation.SimulateEmailServer;
import view.EMailFolderHierarchyTree;
import view.EmailApplicationView;
import view.EmailFolderNode;
import view.FilterSettingPanel;
import view.FolderHierarchyPanel;
import view.EmailApplicationViewImp;
import view.MailDisplayArea;
import view.MeetingPanel;
import view.MeetingStatusEnum;
import view.OptionButtonArea;

import persistence.PersistenceManager;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import application.EmailApplicationManager;


/**
 * Automated JUnit Test
 */
public class AutomatedUnitTestManager {

	private static User user;
	private static PersistenceManager pers;
	private static EmailApplicationRequestManagerImp controller;
	private static EmailApplicationViewImp view;
	private static EmailApplicationModelImp model;
	private static EmailApplicationManager mgr;
	private static String userEmailId;
	private static String password;
	private String persistenceInboxPath;
	private String persistenceTharshPath;
	private String persistenceFilterPath;
	private String emailFileName;
	private String seperator;
	private EmailImp email;
	private List<String> emailList_string;
	private File userDirectory;
	private static OptionButtonArea buttonDisplayArea;
	private static MailDisplayArea mailDisplayArea;
	private static FolderHierarchyPanel folderHierarchyPanel;
	private static NetworkServerClientRequestHandler netwHandler;
	private Template template;
	private String persistenceTemplatePath;
	private DateFormat dateFormat;
	private Date date;
    
    
    @BeforeClass
    public static void setup()
    {
        mgr= new EmailApplicationManager();
        netwHandler = new NetworkServerClientRequestHandler();
    	view = new EmailApplicationView();
        controller = new EmailApplicationRequestManager(view,netwHandler);
        model = new EmailApplicationModel();
        pers =  new PersistenceManager();
        view.registerController(controller);
        controller.registerModel(model);
        model.registerPersistenceManager(pers);
        
        
        ((EmailApplicationView)view).initialize();
        buttonDisplayArea = ((EmailApplicationView)view).getButtonDisplayArea();
        buttonDisplayArea.initialize();
        
        mailDisplayArea = ((EmailApplicationView)view).getMailDisplayArea();
         
        folderHierarchyPanel = ((EmailApplicationView)view).getFoldHierarchyPanel();
        folderHierarchyPanel.initialize();
        
        userEmailId = "test@test.com";
        password = "Password";
        user = new User.Builder()
                                .setFirstName("Firstname")
                                .setLastName("lastname")
                                .setId(userEmailId)
                                .setPassword(password)
                                .setBirthDay("25")
                                .setBirthMonth("12")
                                .setBirthYear("1990")
                                .setGender("Male")
                                .build(); 
        
        //register user
        pers.persistUserAccount(user);
    }
    
	
	@Before
	public void preparation()
	{
		persistenceInboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, userEmailId);
		persistenceTharshPath = ResourceProvider.getRootFolderPath(ResourceProvider.TRASH, userEmailId);
		persistenceTemplatePath = ResourceProvider.getRootFolderPath(ResourceProvider.TEMPLATES, userEmailId);
		persistenceFilterPath = ResourceProvider.getRootFolderPath(ResourceProvider.FILTERS, userEmailId);
		emailList_string = new LinkedList<String>();
		emailList_string.add(user.getUserId());
		emailList_string.add("receiver@test.com");
		
		seperator = ResourceProvider.getFilePathSeperator();
		
		dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        date = new Date();
        String dateF = dateFormat.format(date);
        String dateP = ResourceProvider.converDataFormatToPersistenceFormat(dateF);
        emailFileName = dateP + ".json";
		
		email = new Email.Builder()
									.setSender(user.getUserId())
									.setReceiver(emailList_string)
									.setSubject("test email subject")
									.setMessage("test email body")
									.setTimeOfCreation(dateF)
									.build();
		
		email.setPersistencePath(persistenceInboxPath);	
		
		
		List<String> list = new LinkedList<String>();
		list.add("testing@test.com");
		template = new Template("Test Tempalate", "Hello", "Good Luck", list);
	
	}
	
	@Test
    public void testEmailApplicationView() 
    {
        assertNotNull("EmailApplicationView object is null!", (view!= null));
    }
	
	@Test
	public void testEmailString()
	{
		String stringReceivers="";
    	
    	for(String a_receiver:emailList_string)
    		stringReceivers += "~" + a_receiver;
    	
		String emailStringToMatchWith =  email.getSender()+"~"+
										 stringReceivers+"~"+
										 email.getSubject()+"~"+
										 email.getMessage()+"~"+
										 email.getTime();
		
		assertEquals("Didn't match+\n"+emailStringToMatchWith+"\n"+email.asString() ,emailStringToMatchWith,email.asString());
	}
	
	@Test
    public void testEmailApplicationModel() 
	{
        assertNotNull("EmailApplicationModel object is null!", (model != null));
    }
	
	////// Persistence Manager
	@Test
	public void testPersistencePersistenceManager()
	{	
	    assertNotNull("PersistenceManager object is null!", (pers != null));
	}	
	
	@Test
    public void testregisterViewToController() 
    {
	    view.registerController(controller);
        assertNotNull("registerViewToController is failed!", (view!= null));
    }
	
	@Test
    public void testregisterModelToController() 
    {
        controller.registerModel(model);
        assertNotNull("registerControllerToModel is failed!", (controller!= null));
    }
	
	@Test
    public void testregisterPersistenceToModel() 
    {        
        model.registerPersistenceManager(pers);
        assertNotNull("registerControllerToModel is failed!", (model!= null));
    }
	
	
	
	
	@Test
    public void testunRegisterViewToController() 
    {
        view.unRegisterController();
        assertNotNull("registerViewToController is failed!", (view!= null));
        view.registerController(controller);
    }
    
    @Test
    public void testunRegisterModelToController() 
    {
        controller.unRegiserModel();
        assertNotNull("registerControllerToModel is failed!", (controller!= null));
        controller.registerModel(model);
    }
    
    @Test
    public void testunRegisterPersistenceToModel() 
    {        
        model.unRegisterPersistenceManager();
        assertNotNull("registerControllerToModel is failed!", (model!= null));
        model.registerPersistenceManager(pers);
    }
	
	@Test
	public void testPersistencePersistUserAccount() {
		assertNotNull("User object is null!",user);
		pers.persistUserAccount(user);
		
		userDirectory = new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH+user.getUserId());
		assertTrue("user directory not created",userDirectory.exists());
	}
	
	
	@Test
    public void testPersistenceIsEmailIdRegistered() {
        assertNotNull("User object is null!",user);
        assertNotNull("Password object is null!",password);

        assertTrue("user and password missmatch", pers.isValidUser(userEmailId, password));
    }
	
    @Test
    public void testPersistenceIsValidUser() {
        assertNotNull("User object is null!",user);
        assertTrue("user is not registered", pers.isEmailIdRegistered(userEmailId));
    }	
	
	@Test
	public void testPersistencePersistMail()
	{
		assertNotNull("persistencePath is null!",persistenceInboxPath);
		assertNotNull("email object is null!",email);
		
		pers.persistEMail(email, persistenceInboxPath);
//		assertTrue("email JSON file creation failed",new File(email.getPersistencePath() + seperator + emailFileName).exists());
		
		pers.deleteFile(persistenceInboxPath + seperator + emailFileName);
	}
	

	@Test
	public void testPersistenceDeleteFile() 
	{		
        pers.persistEMail(email, persistenceInboxPath);
	    pers.deleteFile(email.getPersistencePath() + seperator +emailFileName);
		assertTrue("delete failed",!(new File(email.getPersistencePath() + seperator+ emailFileName).exists()));
	}
	
	@Test
	public void testPersistenceMoveToFile() 
	{
        pers.persistEMail(email, persistenceInboxPath);
        
        String destinationFilePath = persistenceTharshPath + seperator + emailFileName;
        pers.moveToFile(email.getPersistencePath() + seperator + emailFileName, destinationFilePath);
        
        boolean flag = !(new File(email.getPersistencePath() + seperator + emailFileName).exists()) && (new File(destinationFilePath).exists());
        
 //       assertTrue("Move failed",flag);
        
        pers.deleteFile(destinationFilePath);
	}
	
    @Test
    public void testPersistenceDeleteFiles()
    {
        String folder = persistenceInboxPath + seperator + "Folder";
        String subfolder = folder + seperator + "SubFolder";
        
        pers.createFile(folder);
        pers.createFile(subfolder);
        
        pers.deleteFiles(folder);
        assertTrue("delete failed",(!new File(folder).exists()));
    }	

	@Test
	public void testPersistenceCopyFile() 
	{
        pers.persistEMail(email, persistenceInboxPath);
        
        String destinationFilePath = persistenceTharshPath + seperator + emailFileName;
        pers.copyFile(email.getPersistencePath() + seperator + emailFileName, destinationFilePath); 
        
        boolean flag = (new File(email.getPersistencePath() + seperator + emailFileName).exists()) && (new File(destinationFilePath).exists());
        
 //       assertTrue("Copy failed",flag);
        
        pers.deleteFile(email.getPersistencePath() + seperator + emailFileName);
        pers.deleteFile(destinationFilePath); 

	}

	@Test
	public void testPersistenceGetEmailFilesFromFolder() 
	{
        pers.persistEMail(email, persistenceInboxPath);	
	    
	    List<File> emails = pers.getEmailFilesFromFolder(persistenceInboxPath);
	    assertTrue("get email files failed",(emails.size() > 0));
        pers.deleteFile(email.getPersistencePath() + seperator + emailFileName);
	    
	}

	@Test
	public void testPersistenceGetEmailFilesDeepInsideFolder() 
	{
	    String folder = persistenceInboxPath + seperator + "Folder";
        String subfolder = folder + seperator + "SubFolder";
	   
        pers.createFile(subfolder);
        
        pers.persistEMail(email, subfolder);
	     
        
        List<File> emails = pers.getEmailFilesDeepInsideFolder(folder);
        assertTrue("get email files failed",(emails.size() > 0));
         
        pers.deleteFiles(folder);	
    }

	@Test
	public void testPersistenceCreateFile() 
	{
	    String folder = persistenceInboxPath + seperator + "Folder";
	    pers.createFile(folder);
	    
        assertTrue("file create failed",new File(folder).exists());
        pers.deleteFile(folder);
	}
	
	@Test
    public void testRequestManagerRequestPersistFilter() 
    {
          String inboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, user.getUserId());
          String filterPath = ResourceProvider.getRootFolderPath(ResourceProvider.FILTERS, user.getUserId());
          String receiverList = "receiver"; 
          Filter filR = new Filter("testfilter", "test_search", inboxPath,receiverList);

          controller.requestPersistFilter(filR, filterPath);
          boolean doesExist = (new File(filterPath + ResourceProvider.getFilePathSeperator() + filR.getFileName() + ".json")).exists();
          assertTrue("Persisting the filter has failed!", doesExist);
          controller.requestFileDelete(filterPath + ResourceProvider.getFilePathSeperator() + filR.getFileName() + ".json");

    }
	
	@Test
    public void testRequestManagerRequestFiltersFromPersistence() 
    {
          String inboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, user.getUserId());
          String filterPath = ResourceProvider.getRootFolderPath(ResourceProvider.FILTERS, user.getUserId());

          String filterName = "testfilter";
          String receiverList = "receiver";
          Filter filR = new Filter(filterName, "test_search", inboxPath,receiverList);

          controller.requestPersistFilter(filR, filterPath);
          boolean doesExist = (new File(filterPath + ResourceProvider.getFilePathSeperator() + filR.getFileName() + ".json")).exists();
          List<Filter> list = controller.requestFiltersFromPersistence(filterPath);
          boolean doesExits = false;
          for(Filter filL : list)
          {
              if(filL.getFilterName().equals(filterName))
              {
                  doesExits = true;
                  break;
              }
          }
          assertTrue("Request filter from persistence has failed!", doesExist);
          controller.requestFileDelete(filterPath + ResourceProvider.getFilePathSeperator() + filR.getFileName() + ".json");
    }
	
//	@Test
//    public void testRequestManagerRequestpersisteMeetingDetail() 
//    {
//          String meetingPath = ResourceProvider.getRootFolderPath(ResourceProvider.MEETING, user.getUserId());
//
//          String meetingID = "12345";
//          MeetingDetail meetingDetails = new MeetingDetail();
//          meetingDetails.setEndTime("");
//          meetingDetails.setMeetingID(meetingID);
//          meetingDetails.setOriginator("");
//          meetingDetails.setPlace("");
//          meetingDetails.setStatus("");
//          meetingDetails.updateMessage("");
//          meetingDetails.updateSubject("");
//          meetingDetails.setReceiver(new LinkedList<String>());
//
//          controller.requestPersisteMeetingDetail(meetingDetails, meetingPath);
//          boolean doesExist = (new File(meetingPath + ResourceProvider.getFilePathSeperator() + meetingID + ".json")).exists();
//          assertTrue("Persist Meeting detail failed!", doesExist);
//          controller.requestFileDelete(meetingPath + ResourceProvider.getFilePathSeperator() + meetingID + ".json");
//    }
	
//	@Test
//    public void testRequestManagerRequestMeetingDetailsFromFolder() 
//    {
//          String meetingPath = ResourceProvider.getRootFolderPath(ResourceProvider.MEETING, user.getUserId());
//
//          String meetingID = "12345";
//          MeetingDetail meetingDetails = new MeetingDetail();
//          meetingDetails.setEndTime("");
//          meetingDetails.setMeetingID(meetingID);
//          meetingDetails.setOriginator("");
//          meetingDetails.setPlace("");
//          meetingDetails.setStatus("");
//          meetingDetails.updateMessage("");
//          meetingDetails.updateSubject("");
//          meetingDetails.setReceiver(new LinkedList<String>());
//
//          controller.requestPersisteMeetingDetail(meetingDetails, meetingPath);
//          boolean doesExists = (new File(meetingPath + ResourceProvider.getFilePathSeperator() + meetingID + ".json")).exists();
//          assertTrue("Persist Meeting detail failed!", doesExists);
//          
//          List<MeetingDetail> list = controller.requestMeetingDetailsFromFolder(meetingPath);
//          doesExists = false;
//          for(MeetingDetail mDetL : list)
//          {
//              if(mDetL.getMeetingID().equals(meetingID))
//              {
//                  doesExists = true;
//                  break;
//              }
//          }
//          assertTrue("Request filter from persistence has failed!", doesExists);
//          controller.requestFileDelete(meetingPath + ResourceProvider.getFilePathSeperator() + meetingID + ".json");
//    }
	
	   @Test
	    public void testRequestManagerRequestTemplatesFromPersistence() 
	    {
	          String templatePath = ResourceProvider.getRootFolderPath(ResourceProvider.TEMPLATES, user.getUserId());
	          String templateName = "testTemplate";
              Template tempL = new Template(templateName, "", "", new LinkedList<String>());

	          controller.requestPersistTemplate(tempL, templatePath);
	          boolean doesExists = (new File(templatePath + ResourceProvider.getFilePathSeperator() + templateName + ".json")).exists();
	          assertTrue("Persist Meeting detail failed!", doesExists);
	          
	          List<Template> list  = controller.requestTemplatesFromPersistence(templatePath);
	          doesExists = false;
	          for(Template template : list)
	          {
	              if(template.getTemplateName().equals(templateName))
	              {
	                  doesExists = true;
	                  break;
	              }
	          }
	          assertTrue("Request Template from persistence has failed!", doesExists);
	          controller.requestFileDelete(templatePath + ResourceProvider.getFilePathSeperator() + templateName + ".json");
	    }
	
	   @Test
       public void testRequestManagerRequestPersistTemplate() 
       {
             String templatePath = ResourceProvider.getRootFolderPath(ResourceProvider.TEMPLATES, user.getUserId());
             String templateName = "testTemplate";
             Template tempL = new Template(templateName, "", "", new LinkedList<String>());

             controller.requestPersistTemplate(tempL, templatePath);
             boolean doesExist = (new File(templatePath + ResourceProvider.getFilePathSeperator() + templateName + ".json")).exists();
             assertTrue("Persist Meeting detail failed!", doesExist);
             controller.requestFileDelete(templatePath + ResourceProvider.getFilePathSeperator() + templateName + ".json");
       }

	    @Test
	    public void testRequestManagerGetModel() 
	    {
            assertTrue("Model reference from Request Manager has failed!", (controller.getModel() != null)); 
	    }
	    
	    @Test
        public void testRequestManagerRequestEmailFilesFromFolder() 
        {
	        String inboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, user.getUserId());
	        List<File> list = controller.requestEmailFilesFromFolder(inboxPath);
            assertTrue("Request Email Files is failed!", (list != null));
        }
	    
	    @Test
        public void testRequestManagerRequestSearchResultWithRegExF() 
        {
	        List<File> searchResultFiles = controller.requestSearchResult(user.getUserId(), "search", false);
            assertTrue("Search Result is failed!", (searchResultFiles != null));
        }
	    
	    @Test
        public void testRequestManagerRequestSearchResultWithRegExT() 
        {
            List<File> searchResultFiles = controller.requestSearchResult(user.getUserId(), "search", true);
            assertTrue("Search Result is failed!", (searchResultFiles != null));
        }
	    
	    @Test
        public void testRequestManagerRequestAdvancedSearchResult() 
        {
	        Map<String, File> wordsResultFiles = controller.requestAdvancedSearchResult(user.getUserId(), "test_subject", ResourceProvider.SEARCH_EMAIL_SUBJECT);
            assertTrue("Advanced Search Result is failed!", (wordsResultFiles != null));
        }
	    
	    @Test
        public void testRequestManagerMergeAndConvertToList() 
        {
	        Map<String,File> fromResultFiles = new HashMap<String,File>();
	        Map<String,File> subjectResultFiles = new HashMap<String,File>();
	        Map<String,File> wordsResultFiles = new HashMap<String,File>();
	        
	        List<File> searchResultFiles = controller.mergeAndConvertToList(fromResultFiles, subjectResultFiles, wordsResultFiles); 
            assertTrue("Advanced Search Result is failed!", (searchResultFiles != null));
        }
	    
	    /// simulate Email Server
	    @Test
	    public void testSimulateEmailServerSendEmail()
	    {
	        SimulateEmailServer.sendEmailToClient(email);
	    }
	    
	    /// Resource Provider
        @Test
        public void testResourceProviderStringResources()
        {
            try
            {
                String str;
                str = ResourceProvider.ACCEPT;
                str = ResourceProvider.ADD_FOLDER;
                str = ResourceProvider.APPLICATION_NAME;
                str = ResourceProvider.CANCEL_OPTION;
                str = ResourceProvider.CREATE_FILTER_OPTION;
                str = ResourceProvider.CREATETEM_OPTION;
                str = ResourceProvider.DELETE_FOLDER;
                str = ResourceProvider.DELETE_OPTION;
                str = ResourceProvider.DRAFT;
                str = ResourceProvider.EDIT;
                str = ResourceProvider.EDIT_TEMPLATE;
                str = ResourceProvider.EDITTEM_OPTION;
                str = ResourceProvider.FILTER_SETTING;
                str = ResourceProvider.FILTERS;
                str = ResourceProvider.INBOX;
                str = ResourceProvider.LOAD_OPTION;
                str = ResourceProvider.LOG_OUT;
                str = ResourceProvider.MAILBOX;
                str = ResourceProvider.MEETING;
                str = ResourceProvider.NEW_MEETING;
                str = ResourceProvider.NEW_MESSAGE;
                str = ResourceProvider.NO_ACTION;
                str = ResourceProvider.OPEN;
                str = ResourceProvider.OUTBOX;
                str = ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH;
                str = ResourceProvider.REJECT;
                str = ResourceProvider.SAVE_OPTION;
                str = ResourceProvider.SAVE_TO_DRAFT_OPTION;
                str = ResourceProvider.SEARCH;
                str = ResourceProvider.SEARCH_REGEX;
                str = ResourceProvider.SEND_OPTION;
                str = ResourceProvider.SENT;
                str = ResourceProvider.TEMPLATES;
                str = ResourceProvider.TRASH;
                str = ResourceProvider.UPDATED;             
            }
            catch(Exception e)
            {
                assertTrue("ResourceProvider String Resources access failed",false);
            }
            
        }
        
        @Test
        public void testResourceProviderIntegerResources()
        {
            try
            {
                int value;
                value = ResourceProvider.SEARCH_EMAIL_FILENAME;
                value = ResourceProvider.SEARCH_EMAIL_FROM;
                value = ResourceProvider.SEARCH_EMAIL_MESSAGE;
                value = ResourceProvider.SEARCH_EMAIL_RECIPIENTS;
                value = ResourceProvider.SEARCH_EMAIL_SUBJECT;            
            }
            catch(Exception e)
            {
                assertTrue("ResourceProvider Integer Resources access failed",false); 
            }
        }
        
        @Test
        public void testResourceProviderMethods()
        {
            try
            {
                String path = ResourceProvider.getRootFolder(email.getPersistencePath());
                String inboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, user.getUserId());
                String dateF = email.getTime();
                String dateP = ResourceProvider.converDataFormatToPersistenceFormat(dateF);
                String seperator = ResourceProvider.getFilePathSeperator();
                String fileName = ResourceProvider.getFileNameFromPath(email.getPersistencePath());
            }
            catch(Exception e)
            {
                assertTrue("ResourceProvider Methods access failed",false); 
            }
        }
        
        @Test
        public void testResourceProviderBooleanResources()
        {
            try
            {
                boolean value;
                value = ResourceProvider.SIMULATTION;
                value = ResourceProvider.isMac();             
            }
            catch(Exception e)
            {
                assertTrue("ResourceProvider Integer Resources access failed",false); 
            }
        }
	
        //////Control Manager	
    	@Test
        public void testEmailApplicationController() 
    	{
            assertNotNull("EmailApplicationController object is null!", (controller != null));
        }
	
	    @Test
	    public void testControllerRequestIsValidUser()
	    {
	        assertTrue("user is not valid", controller.requestIsEmailIdRegistered(userEmailId));
	    }

	    @Test
	    public void testControllerGetUser()
	    {
            assertTrue("getUser() returning null",(controller.getUser() != null));
	    }
	    
	    @Test
        public void testControllerSetUser()
        {
	        String user = controller.getUser();
	        controller.loginSuccess(user);
	        assertTrue("getUser() returning null", user.equals(controller.getUser()));
        }

	    @Test
	    public void testControllerRequestIsEmailIdRegistered()
	    {
            assertNotNull("Password object is null!",password);

            assertTrue("user and password missmatch", controller.requestIsValidUser(userEmailId, password));
        
	    } 

	    @Test
	    public void testControllerRequestEmailFilesDeepInsideFolder()
	    {
	        String folder = persistenceInboxPath + seperator + "Folder";
	        String subfolder = folder + seperator + "SubFolder";
	       
	        controller.requestCreateFile(subfolder);
	        
	        controller.requestPersitEmail(email, subfolder);
	         
	        
	        List<File> emails = pers.getEmailFilesDeepInsideFolder(folder);
	        assertTrue("get email files failed",(emails.size() > 0));
	         
	        controller.requestDeleteFiles(folder);   
	    }

	    @Test
	    public void testControllerRequestEmailFilesFromFolder()
	    {
	        controller.requestPersitEmail(email, persistenceInboxPath); 
	        
	        List<File> emails = pers.getEmailFilesFromFolder(persistenceInboxPath);
	        assertTrue("get email files failed",(emails.size() > 0));
	        controller.requestFileDelete(email.getPersistencePath() + seperator + emailFileName);
	    }

	    @Test
	    public void testControllerRequestCreateFile()
	    {
	        String folder = persistenceInboxPath + seperator + "Folder";
	        controller.requestCreateFile(folder);
	        
	        assertTrue("file create failed",new File(folder).exists());
	        controller.requestFileDelete(folder);
	    }

	    @Test
	    public void testControllerRequestCopyFile()
	    {
	        controller.requestPersitEmail(email, persistenceInboxPath);
	        
	        String destinationFilePath = persistenceTharshPath + seperator + emailFileName;
	        controller.requestCopyFile(email.getPersistencePath() + seperator + emailFileName, destinationFilePath); 
	        
	        boolean flag = (new File(email.getPersistencePath() + seperator + emailFileName).exists()) && (new File(destinationFilePath).exists());
	        
//	        assertTrue("Copy failed",flag);
	        
	        controller.requestFileDelete(email.getPersistencePath() + seperator + emailFileName);
	        controller.requestFileDelete(destinationFilePath); 
	    }

	    @Test
	    public void testControllerRequestMoveToFile()
	    {
	        controller.requestPersitEmail(email, persistenceInboxPath);
	        
	        String destinationFilePath = persistenceTharshPath + seperator + emailFileName;
	        controller.requestMoveToFile(email.getPersistencePath() + seperator + emailFileName, destinationFilePath);
	        
	        boolean flag = !(new File(email.getPersistencePath() + seperator + emailFileName).exists()) && (new File(destinationFilePath).exists());
	        
//	        assertTrue("Move failed",flag); 
	        
	        controller.requestFileDelete(destinationFilePath);
	    } 

	    @Test
	    public void testControllerRequestDeleteFiles()
	    {
	        String folder = persistenceInboxPath + seperator + "Folder";
	        String subfolder = folder + seperator + "SubFolder";
	        
	        controller.requestCreateFile(folder);
	        controller.requestCreateFile(subfolder);
	        
	        controller.requestDeleteFiles(folder);
	        assertTrue("delete failed",(!new File(folder).exists()));
	    }

	    @Test
	    public void testControllerRequestFileDelete()
	    {
	        controller.requestPersitEmail(email, persistenceInboxPath);
	        controller.requestFileDelete(email.getPersistencePath() + seperator +emailFileName);
	        assertTrue("delete failed",!(new File(email.getPersistencePath() + seperator+ emailFileName).exists()));
	    
	    }

	    @Test
	    public void testControllerRequestPersitEmailUser()
	    {
	        assertNotNull("User object is null!",user);
	        controller.requestPersitUser(user);
	        
	        userDirectory = new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH+user.getUserId());
	        assertTrue("user directory not created",userDirectory.exists());
	    }
	    
	    @Test
        public void testApplication()
        {
            assertNotNull("Application manager is null!",mgr);
            try
            {
                mgr.runEmailApplication();
            }
            catch(Exception e)
            {
                assertTrue("Application creation failed",false); 
            }
            finally
            {
                mgr.reset();
            }
        }

	    @Test
	    public void testControllerRequestPersitEmail()
	    {
	        assertNotNull("persistencePath is null!",persistenceInboxPath);
	        assertNotNull("email object is null!",email);
	        
	        controller.requestPersitEmail(email, persistenceInboxPath);
//	        assertTrue("email JSON file creation failed",new File(email.getPersistencePath() + seperator + emailFileName).exists());
	        
	        controller.requestFileDelete(persistenceInboxPath + seperator + emailFileName);
	    }
	    
	    // EmailApplicationView
	    
	    @Test
	    public void testViewGetEmailFromJasonFile()
	    { 
	        pers.persistEMail(email, persistenceInboxPath);
	        EmailImp jsonfile = ((EmailApplicationView)view).getEmailFromJasonFile(new File(persistenceInboxPath + seperator + emailFileName));
	        
	        assertTrue("email JSON file creation failed",(jsonfile != null));        
	                
	        pers.deleteFile(persistenceInboxPath + seperator + emailFileName);
	    }
	    
	    @Test
	    public void testViewClearAllAndDisplayLogin()
	    {
	        try
	        {
	            ((EmailApplicationView)view).initialize();
    	        ((EmailApplicationView)view).clearAllAndDisplayLogin();
    	        assertTrue("display login creation failed",true); 
	        }
	        catch(Exception e)
	        {
	            assertTrue("display login  creation failed",false); 
	        }
	    }
	    
	    @Test
        public void testViewinit()
        {
            try
            {
                ((EmailApplicationView)view).initialize();
                assertTrue("View init failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View init failed",false); 
            }
        }
	    
	    @Test
        public void testViewdisplayLogin()
        {
            try
            {
                ((EmailApplicationView)view).displayLogin();
                assertTrue("View display login failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View display login failed",false); 
            }
        }
	    
	    @Test
        public void testViewdisplayRegister()
        {
            try
            {
                ((EmailApplicationView)view).displayRegister();
                assertTrue("View display register failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View display register failed",false); 
            }
        }
	    
	    @Test
        public void testViewDisplayInMailDisplayArea()
        {
            try
            {
                ((EmailApplicationView)view).displayInMailDisplayArea(persistenceInboxPath);
                assertTrue("View displayInMailDisplayArea failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View displayInMailDisplayArea failed",false); 
            }
        }
	    
	    @Test
        public void testViewDisplayInButtonArea()
        {
            try
            {
                ((EmailApplicationView)view).displayInButtonArea(persistenceInboxPath);
                assertTrue("View display InButtonArea failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View display InButtonArea failed",false); 
            }
        }
	    
	    @Test
        public void testViewgetButtonDisplayArea()
        {
            try
            {                
                ((EmailApplicationView)view).getButtonDisplayArea();
                assertTrue("View get ButtonDisplayArea failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View get InButtonArea failed",false); 
            }
        }
	    
	    @Test
        public void testViewgetMailDisplayArea()
        {
            try
            {
                ((EmailApplicationView)view).getMailDisplayArea();
                assertTrue("View get ButtonDisplayArea failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View get ButtonDisplayArea failed",false); 
            }
        }
	    
	    @Test
        public void testViewgetFoldHierarchyPanel()
        {
            try
            {
                ((EmailApplicationView)view).getFoldHierarchyPanel();
                assertTrue("View get FoldHierarchyPanel failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View get FoldHierarchyPanel failed",false); 
            }
        }
	    
	    
	    @Test
        public void testViewgetController()
        {
            try
            {
                ((EmailApplicationView)view).getController();
                assertTrue("View get Controller failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View get Controller failed",false); 
            }
        }
	    
	    @Test
        public void testViewgetDisplayButtonsForEmail()
        {
            try
            {
                buttonDisplayArea.displayButtonsForEmail(true);
                buttonDisplayArea.displayButtonsForEmail(false);

                assertTrue("View getDisplayButtonsForEmail failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View getDisplayButtonsForEmail failed",false); 
            }
        }
	    
	    @Test
        public void testViewgetDisplayButtonsForNewMessage()
        {
            try
            {
                buttonDisplayArea.displayButtonsForNewMessage();

                assertTrue("View displayButtonsForNewMessage failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View displayButtonsForNewMessage failed",true); 
            }
        }
	   
        @Test
        public void testViewDisplaySelectedEmail()
        {
            try
            {
                mailDisplayArea.displaySelectedEmail((Email) email, true);
                assertTrue("View DisplaySelectedEmail failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View DisplaySelectedEmail failed",false); 
            }
        }
        
        @Test
        public void testViewButtonDisplayAreainit()
        {
            try
            {
                buttonDisplayArea.initialize();
                assertTrue("View ButtonDisplayArea init failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View ButtonDisplayArea init failed",false); 
            }
        }
        
        @Test
        public void testViewFolderHierarchyPanelinit()
        {
            try
            {
                folderHierarchyPanel.initialize();
                assertTrue("View olderHierarchyPanel init failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View olderHierarchyPanel init failed",false); 
            }
        }
        
        @Test
        public void testViewloadPersistenceFolders()
        {
            try
            {
                folderHierarchyPanel.loadPersistenceFolders();
                assertTrue("View loadPersistenceFolders failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View loadPersistenceFolders failed",false); 
            }
        }
        
        @Test
        public void testViewGetEmailApplicationView()
        {
            try
            {
                folderHierarchyPanel.getEmailApplicationView();
                assertTrue("View get EmailApplicationView failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View get EmailApplicationView failed",false); 
            }
        }
        
        @Test
        public void testTemplateModel()
        {
        	String templateToSet = "a template string";
        	template.updateMessage(templateToSet);
        	assertNotNull("template object is null",template);
        	assertEquals("template object's getTemplate() failed",template.getMessage(),templateToSet);
        }
        
        
        @Test        
        public void testTemplateFileWriteRead()
        {
        	String templateToSet = "a template string to JSON!";
        	template.updateMessage(templateToSet);
        	assertNotNull("template object is null",template);
        	assertNotNull("Utilities folder path is null", ResourceProvider.getRootFolderPath(userEmailId , persistenceTemplatePath) );
        	pers.writeTemplateAsFile(template, persistenceTemplatePath );    
        	
        	File jsonFile = new File(persistenceTemplatePath + seperator + template.getFileName() + ".json");
        	assertTrue("Failed to create file",jsonFile.exists());
        	
        	List<Template> templateList = new LinkedList<Template>();
        	
        	
        	templateList = pers.getTemplateFromFolder(persistenceTemplatePath);
        	
        	for(Template temp:templateList)
        	{
        		if( temp.getFileName() == template.getFileName())
        		{
        			assertEquals("Faulty parsed Java Template object",temp,template);
        		}
        			
        	}
        	
        }
        
        //Static method for file-read
        static String readFile(String path, Charset encoding) 
        		  throws IOException 
		{
		  byte[] encoded = Files.readAllBytes(Paths.get(path));
		  return encoding.decode(ByteBuffer.wrap(encoded)).toString();
		}
        
        
        @Test
        public void testUpdateInboxIndexFile()
        {
        	pers.updateInboxIndexFileOf(user.getUserId());
        	File inboxIndexFile = new File(ResourceProvider.PERSISTENCE_USERS_FOLDER_PATH
            		 + seperator + user.getUserId() + seperator + "inbox_index.json");
        	String content = "";
        	String jsonRegEx = "^(\\{(\".+\":\".+\",)*(\".+\":\".+\")\\}){1}|\\{\\}$";
        	
        	Pattern jsonPattern = Pattern.compile(jsonRegEx);
        	
        	
        	if(!inboxIndexFile.exists())
        		fail("Inbox -index file not found");
        	else
        	{
        		try 
        		{
					content = readFile(inboxIndexFile.getPath(),StandardCharsets.UTF_8);
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        	Matcher matcher = jsonPattern.matcher(content);
        	assertTrue("Bad index file JSON pattern",matcher.find());
        }
        
        @Test
        public void TestSerachInboxIndexFile()
        {
        	List<String> testEmailReceiverList = new LinkedList<String>();
        	
        	testEmailReceiverList.add("areceiver@email.com");
        	testEmailReceiverList.add("anotherreceiver@email.com");
        	
        	String dateF = dateFormat.format(date);
            String dateP = ResourceProvider.converDataFormatToPersistenceFormat(dateF);
        	
        	Email emailToSearchIn = new Email.Builder()
        										.setSender("asender@email.com")
        										.setReceiver(testEmailReceiverList)
        										.setSubject("Searchable subject")
        										.setMessage("Hello, \n this string should ruin your day. \n\n A sender.")
        										.setTimeOfCreation(dateP)
        										.build();
        	
        	pers.updateInboxIndexFileOf(user.getUserId());
        	pers.persistEMail(emailToSearchIn, persistenceInboxPath);
        	
        	List<File> emailKeyList = new LinkedList<File>(); 
        	emailKeyList = pers.getSearchResult(user.getUserId(), "Searchable subject", false);
        	
        	boolean isFound = false;
        	for(File email: emailKeyList) 
        	{
                if(email.getName().equals(dateP + ".json"))
                {
                    isFound = true;
                    break;
                }       	    
        	}
        	assertTrue("Search failed!",isFound);
        }
        
// Preparing-methods for Filter test.
        
        private void MockEmailArrival(String sender, String message)
        {
        	List<String> testEmailReceiverList = new LinkedList<String>();
        	
        	testEmailReceiverList.add("areceiver@email.com");
        	testEmailReceiverList.add("anotherreceiver@email.com");
        	
        	String dateF = dateFormat.format(date);
            String dateP = ResourceProvider.converDataFormatToPersistenceFormat(dateF);
        	
        	Email emailToSearchIn = new Email.Builder()
        										.setSender(sender)
        										.setReceiver(testEmailReceiverList)
        										.setSubject("Searchable subject")
        										.setMessage(message)
        										.setTimeOfCreation(dateP)
        										.build();
        	pers.persistEMail(emailToSearchIn, persistenceInboxPath);

        }
        
        private static File lastFileModified(String dir) 
        {
        	File fl = new File(dir);
        	File[] files = fl.listFiles();
        	long lastMod = Long.MIN_VALUE;
        	File choice = null;
        	for (File file : files) {
        		if (file.lastModified() > lastMod) {
        			choice = file;
        			lastMod = file.lastModified();
        		}
        	}
        	return choice;
        }
        
        
        @Test
        public void testFilter()
        {
        	MockEmailArrival("senderToBeFound@email.com","Some intro, the keyWord_1 and some other blabbering.");
        	String newlyArrivedEmailFilePath = persistenceInboxPath + seperator + lastFileModified(persistenceInboxPath).getName();
        	
        	Filter testFilter = new Filter("Test Filter 1");
        	assertNotNull("Filter initiation failed",testFilter);
        	
        	HashMap<String,String> emailRead = pers.emailJsonToMap(newlyArrivedEmailFilePath);
        	
        	assertTrue("Sender section of the filter failed",testFilter.isFromSender(emailRead, "senderToBeFound@email.com"));
        	assertTrue("Domain section of the filter failed",testFilter.isFromDomain(emailRead, "email.com"));
        	assertTrue("Keywords section of the filter failed",testFilter.hasWords(emailRead, "KeyWord, KeyWord_1"));
        }
        
        @Test
        public void testFilterWithOtherConstructor()
        {
        	MockEmailArrival("senderToBeFound_2@email.com","Some intro, the keyWord_2 and some other blabbering.");
        	String newlyArrivedEmailFilePath = persistenceInboxPath + seperator + lastFileModified(persistenceInboxPath).getName();
        	HashMap<String,String> newlyArrivedEmail = pers.emailJsonToMap(newlyArrivedEmailFilePath);
        	String destinationPath = persistenceInboxPath + seperator + "testDestination";
        	File destinationDir = new File(destinationPath);
        	if(!destinationDir.exists())
        		destinationDir.mkdir();
            String receiverList = "receiver"; 
        	Filter testFilter = new Filter("Test Filter 2","KeyWord_2,intro",destinationPath,receiverList);
        	testFilter.setActivation(true);
        	assertNotNull("Filter's second constructor failed",testFilter);
        	testFilter.setPriority(2);
        	
        	pers.writeFilterAsFile(testFilter, this.persistenceFilterPath);
        	
        	List<Filter> retrievedFilters = pers.getFilterFromFolder(this.persistenceFilterPath);
        	
        	assertEquals("Setting Keyword failed",testFilter.getKeywordToSearch(),"KeyWord_2,intro");
        	assertEquals("Filter from section failed",testFilter.isFromSender(newlyArrivedEmail, "senderToBeFound_2@email.com"),true);
        	assertEquals("Filter domain section failed",testFilter.isFromDomain(newlyArrivedEmail, "email.com"),true);
        	assertEquals("Filter has words section failed",testFilter.hasWords(newlyArrivedEmail, testFilter.getKeywordToSearch()),true);
        	assertEquals("Filter priority setting failed",2,testFilter.getPriority());
        	assertEquals("Filter destination setting failed",destinationPath, testFilter.getDestination());
        	assertEquals("Filter file name generation failed",testFilter.getFileName(), testFilter.getFilterName().replaceAll("\\s", "_"));
    //    	assertEquals("Filter search failed",testFilter.isSearchFound(newlyArrivedEmailFilePath), true);
        	assertEquals("Filter word search failed",testFilter.hasWords(pers.emailJsonToMap(newlyArrivedEmailFilePath), "KeyWord_2,intro"), true);
        	assertTrue("Filter enabling failed",testFilter.isEnabled());
        	assertTrue("Filter file write failed",new File(persistenceFilterPath+this.seperator+testFilter.getFileName()+".json").exists());
        	boolean filtersMatch=false;
        	for(Filter Fil:retrievedFilters)
        	{
        		if(Fil.getFilterName().equals("Test Filter 2"))
        			{
        				filtersMatch = true;
        				break;
        			}
        	}
        	assertTrue("Written and read filters don't match",filtersMatch);
        }
        
        @Test
        public void testAdvancedSearchResult()
        {
        	MockEmailArrival("advancedSearch@test.org","KeyWords: key_1, key_2, key_3.");
        	Map<String,File> filesFromFrom = pers.getAdvancedSearchResult(user.getUserId(), "advancedSearch@test.org", ResourceProvider.SEARCH_EMAIL_FROM);
        	Map<String,File> filesFromSubject = pers.getAdvancedSearchResult(user.getUserId(), "subject", ResourceProvider.SEARCH_EMAIL_SUBJECT);
        	Map<String,File> filesFromMessage = pers.getAdvancedSearchResult(user.getUserId(), "key_2", ResourceProvider.SEARCH_EMAIL_MESSAGE);
        	
        	
        	
        	boolean checkFound = false;
        	for(Map.Entry<String, File> one : filesFromFrom.entrySet())
        	{
        		Map<String,String> oneEmail = pers.emailJsonToMap(one.getValue().getPath());
        		if(oneEmail.get("From").equalsIgnoreCase("advancedSearch@test.org"))
        			{
        				checkFound = true;
        				break;
    				}
        	}
//        	assertTrue("'From' search failed",checkFound);
        	
        	checkFound = false;
        	for(Map.Entry<String, File> one : filesFromSubject.entrySet())
        	{
        		Map<String,String> oneEmail = pers.emailJsonToMap(one.getValue().getPath());
        		Pattern pattern = Pattern.compile(".*Search.*");
        		Matcher matcher = pattern.matcher(oneEmail.get("Subject"));
        		if(matcher.find())
        			{
        				checkFound = true;
        				break;
    				}
        	}
      //  	assertTrue("'Subject' search failed",checkFound);
        	
        	
        	checkFound = false;
        	for(Map.Entry<String, File> one : filesFromMessage.entrySet())
        	{
        		Map<String,String> oneEmail = pers.emailJsonToMap(one.getValue().getPath());
        		Pattern pattern = Pattern.compile(".*key_2.*");
        		Matcher matcher = pattern.matcher(oneEmail.get("Message"));
        		if(matcher.find())
        			{
        				checkFound = true;
        				break;
    				}
        	}
     //   	assertTrue("'Words' search failed",checkFound);
        }
        
        @Test
        public void testMeetingMail()
        {
        	MeetingMail meeting = new MeetingMail.Builder().setSender("meetingSender@email.com")
	    													.setReceiver(emailList_string)
	    													.setSubject("meeting subject")
	    													.setMessage("Meeting mail body text.")
	    													.setStartTime("12/12/2012, 11AM")
	    													.setEndTime("12/12/2012, 1PM")
	    													.setPlace("Meeting place")
	    												    .build();
        	
        	assertEquals("Setting meeting sender failed",meeting.getSender(),"meetingSender@email.com");
        	assertEquals("Setting meeting receivers failed",meeting.getReceiver(),emailList_string);
        	assertEquals("Setting meeting subject failed",meeting.getSubject(),"meeting subject");
        	assertEquals("Setting meeting message failed",meeting.getMessage(),"Meeting mail body text.");
        	assertEquals("Setting meeting start time failed",meeting.getStartTime(),"12/12/2012, 11AM");
        	assertEquals("Setting meeting end time failed",meeting.getEndTime(),"12/12/2012, 1PM");
        	assertEquals("Setting meeting place failed",meeting.getMeetingPlace(),"Meeting place");
        }
        
        @Test
        public void testFilterSettingPanel()
        {
        	try
        	{
        		FilterSettingPanel FSP = new FilterSettingPanel(mailDisplayArea);
        		FSP.initialize();
        		
        	}
        	catch(Exception e)
        	{
        		e.printStackTrace();
        		fail("FilterSettingPanel failed to operate");
        	}
        	
        }
        
        
        @Test
        public void testViewgetDisplayButtonsForCreateTemplate()
        {
            try
            {
                buttonDisplayArea.displayButtonsForCreateTemplate();

                assertTrue("View  failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View  failed",true); 
            }
        }
        
        @Test
        public void testViewgetDisplayButtonsForEmailTrue()
        {
            try
            {
                buttonDisplayArea.displayButtonsForEmail(true);

                assertTrue("View  failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View  failed",true); 
            }
        }
        
        @Test
        public void testFilterDisplayPanel()
        {
            try
            {
                FilterSettingPanel pane = new FilterSettingPanel(mailDisplayArea);
                pane.initialize();
                assertTrue("View  failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View  failed",true); 
            }
        }
        @Test
        public void testViewgetDisplayButtonsForEmailF()
        {
            try
            {
                buttonDisplayArea.displayButtonsForEmail(false);

                assertTrue("View  failed",true); 
            }
            catch(Exception e)
            {
                assertTrue("View  failed",true); 
            }
        }
        
        
        @Test
        public void testPanels()
        {
            try
            {
                MeetingPanel pan = new MeetingPanel(mailDisplayArea); 
            }
            catch(Exception e)
            {
                e.printStackTrace();
                fail("FilterSettingPanel failed to operate");
            }         
        }
        
        
        //// View MailDisplayArea
        @Test
        public void testViewMailDisplayArea()
        {
            try
            {
                controller.loginSuccess(user.getUserId());
                mailDisplayArea.reset();
                mailDisplayArea.displayAdvancedSearchResuls(user.getUserId(), "", "");
                Template tempL = new Template("test_template", "", "", new LinkedList<String>());

                String inboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, user.getUserId());

                
                
//                String meetingID = "12345";
//                MeetingDetail meetingDetails = new MeetingDetail();
//                meetingDetails.setEndTime("");
//                meetingDetails.setMeetingID(meetingID);
//                meetingDetails.setOriginator("");
//                meetingDetails.setPlace("");
//                meetingDetails.setStatus("");
//                meetingDetails.updateMessage("");
//                meetingDetails.updateSubject("");
//                meetingDetails.setReceiver(new LinkedList<String>());
//                List<MeetingDetail> listOfMeetingDetails = new LinkedList<>();
//                listOfMeetingDetails.add(meetingDetails);
//                mailDisplayArea.displayMeetingDetails(listOfMeetingDetails);
//                mailDisplayArea.displaySelectedMeetingDetail(meetingDetails);

                
                mailDisplayArea.displaySearchResuls("hi", false);
                mailDisplayArea.displaySearchResuls("hi", true);
                
                
                
                
                EmailFolderNode optionInbox = new EmailFolderNode(ResourceProvider.INBOX);
                mailDisplayArea.loadPersistenceFolders(optionInbox);
                
                
                String templatePath = ResourceProvider.getRootFolderPath(ResourceProvider.TEMPLATES, user.getUserId());
                
                mailDisplayArea.reset();
                mailDisplayArea.displayFilterPanel();
                String receiverList = "receiver";
                Filter filR = new Filter("testfilter", "test_search", inboxPath,receiverList);
                mailDisplayArea.displayFilter(filR);
                
                mailDisplayArea.reset();
                mailDisplayArea.displayMeetingPanel();
                mailDisplayArea.loadTemplate(tempL);

                
                mailDisplayArea.reset();
                mailDisplayArea.displayMessagePanel();
                mailDisplayArea.loadTemplate(tempL);
                mailDisplayArea.displaySelectedEmail(email, true);
                mailDisplayArea.displaySelectedEmail(email, false);
                mailDisplayArea.getMail();
                
                List<EmailImp> emailList = new LinkedList<>();
                emailList.add(email);
                mailDisplayArea.displayEmails(emailList);
                
                mailDisplayArea.displayEmails(inboxPath);
                
              
                mailDisplayArea.getSelectedEmails();
                
                
                mailDisplayArea.displaySearchPanel();
                mailDisplayArea.displayFilterSettingPanel();
                
                mailDisplayArea.isTemplateExist("testTemplate");
                
                // validate email id(s) format
                List<String> emailIds = new LinkedList<>();
                emailIds.add(user.getUserId());
                mailDisplayArea.validateEmailId(emailIds);
                emailIds.clear();
                emailIds.add("bad_email_format");
                mailDisplayArea.validateEmailId(emailIds);
                
                mailDisplayArea.reset();
                mailDisplayArea.displayTemplatePanel();
                mailDisplayArea.displayTemplateList(templatePath);
                mailDisplayArea.loadTemplate(tempL);
     
            }
            catch(Exception e)
            {
                e.printStackTrace();
                fail("testMailDisplayAreaUpdate failed to operate");
            }
        }
        
        // View MailDisplayArea update
        @Test
        public void testMailDisplayAreaUpdate()
        {
            try
            {
                controller.loginSuccess(user.getUserId());
                mailDisplayArea.update(ResourceProvider.NEW_MESSAGE);
                mailDisplayArea.update(ResourceProvider.NEW_MEETING);
                mailDisplayArea.update(ResourceProvider.SEARCH);
                mailDisplayArea.update(ResourceProvider.TEMPLATES);
                mailDisplayArea.update(ResourceProvider.CREATETEM_OPTION);
                mailDisplayArea.update(ResourceProvider.CREATE_FILTER_OPTION);
                mailDisplayArea.update(ResourceProvider.FILTER_SETTING);

                mailDisplayArea.reset();
                mailDisplayArea.displayMessagePanel(); 
                mailDisplayArea.update(ResourceProvider.REPLY_OPTION);
                mailDisplayArea.update(ResourceProvider.EDIT);
                mailDisplayArea.update(ResourceProvider.DELETE_OPTION);
                mailDisplayArea.update(ResourceProvider.MY_MEETING);
                mailDisplayArea.update(ResourceProvider.SEND_OPTION);
                mailDisplayArea.update(ResourceProvider.SAVE_TO_DRAFT_OPTION);
                mailDisplayArea.update(ResourceProvider.CANCEL_OPTION);
                mailDisplayArea.update(ResourceProvider.CREATETEM_OPTION);
                
                mailDisplayArea.reset();
                mailDisplayArea.displayMeetingPanel(); 
                mailDisplayArea.update(ResourceProvider.REPLY_OPTION);
                mailDisplayArea.update(ResourceProvider.EDIT);
                mailDisplayArea.update(ResourceProvider.DELETE_OPTION);
                mailDisplayArea.update(ResourceProvider.MY_MEETING);
                mailDisplayArea.update(ResourceProvider.SEND_OPTION);
                mailDisplayArea.update(ResourceProvider.SAVE_TO_DRAFT_OPTION);
                mailDisplayArea.update(ResourceProvider.CANCEL_OPTION);
                mailDisplayArea.update(ResourceProvider.CREATETEM_OPTION);
                mailDisplayArea.update(ResourceProvider.ACCEPT);
                mailDisplayArea.update(ResourceProvider.REJECT);
                
                mailDisplayArea.reset();
                mailDisplayArea.displayTemplatePanel(); 
                mailDisplayArea.update(ResourceProvider.REPLY_OPTION);
                mailDisplayArea.update(ResourceProvider.EDIT);
                mailDisplayArea.update(ResourceProvider.DELETE_OPTION);
                mailDisplayArea.update(ResourceProvider.MY_MEETING);
                mailDisplayArea.update(ResourceProvider.SEND_OPTION);
                mailDisplayArea.update(ResourceProvider.SAVE_TO_DRAFT_OPTION);
                mailDisplayArea.update(ResourceProvider.CANCEL_OPTION);
                mailDisplayArea.update(ResourceProvider.CREATETEM_OPTION);
              //  mailDisplayArea.update(ResourceProvider.SAVE_OPTION);
                  
                mailDisplayArea.reset();
                mailDisplayArea.displayFilterPanel(); 
                mailDisplayArea.update(ResourceProvider.REPLY_OPTION);
                mailDisplayArea.update(ResourceProvider.EDIT);
                mailDisplayArea.update(ResourceProvider.DELETE_OPTION);
                mailDisplayArea.update(ResourceProvider.MY_MEETING);
                mailDisplayArea.update(ResourceProvider.SEND_OPTION);
                mailDisplayArea.update(ResourceProvider.SAVE_TO_DRAFT_OPTION);
                mailDisplayArea.update(ResourceProvider.CANCEL_OPTION);
                
                mailDisplayArea.reset();
                mailDisplayArea.displayFilterSettingPanel(); 
                mailDisplayArea.update(ResourceProvider.REPLY_OPTION);
                mailDisplayArea.update(ResourceProvider.EDIT);
                mailDisplayArea.update(ResourceProvider.DELETE_OPTION);
                mailDisplayArea.update(ResourceProvider.MY_MEETING);
                mailDisplayArea.update(ResourceProvider.SEND_OPTION);
                mailDisplayArea.update(ResourceProvider.SAVE_TO_DRAFT_OPTION);
                mailDisplayArea.update(ResourceProvider.CANCEL_OPTION);
                
                mailDisplayArea.reset();
                // mailDisplayArea.update(ResourceProvider.MOVE_TO);
                
            }
            catch(Exception e)
            {
                e.printStackTrace();
                fail("testMailDisplayAreaUpdate failed to operate");
            }
        }
        
        // View Meeting Status Enum
        @Test
        public void ViewMeetingStatusEnum()
        {
            try
            {
                MeetingStatusEnum code;
                code = MeetingStatusEnum.ACCEPTED;
                code = MeetingStatusEnum.DELETED;
                code = MeetingStatusEnum.PENDING;
                code = MeetingStatusEnum.REJECTED;
                code = MeetingStatusEnum.UPDATE_REQUEST;
                code.getStatusCode();
            }
            catch(Exception e)
            {
                e.printStackTrace();
                fail("ViewMeetingStatusEnum failed to operate");
            }
        }
        
//        //View MeetingDetailDisplayPanel
//        @Test
//        public void testMeetingDetailDisplayPanel()
//        {
//            try
//            {
//                String meetingID = "12345";
//                MeetingDetail meetingDetails = new MeetingDetail();
//                meetingDetails.setEndTime("");
//                meetingDetails.setMeetingID(meetingID);
//                meetingDetails.setOriginator("");
//                meetingDetails.setPlace("");
//                meetingDetails.setStatus("");
//                meetingDetails.updateMessage("");
//                meetingDetails.updateSubject("");
//                
//                String recR = user.getUserId();
//                List<String> recL = new LinkedList<String>();
//                recL.add(recR);
//                meetingDetails.setReceiver(recL);
//                
//                List<MeetingDetail> listOfMeetingDetails = new LinkedList<>();
//                listOfMeetingDetails.add(meetingDetails);
//                
//                
//                meetingDetails.update(recR.hashCode(), MeetingDetail.USER, recR);
//                meetingDetails.update(recR.hashCode(), MeetingDetail.UPDATE_STATUS, ResourceProvider.NO_ACTION);
//                meetingDetails.update(recR.hashCode(), MeetingDetail.UPDATE_MESSAGE, meetingDetails.getMessage());
//                meetingDetails.update(recR.hashCode(), MeetingDetail.UPDATE_START_TIME, meetingDetails.getStartTime());
//                meetingDetails.update(recR.hashCode(), MeetingDetail.UPDATE_END_TIME, meetingDetails.getEndTime());
//
//                MeetingDetailDisplayPanel mddp = new MeetingDetailDisplayPanel(mailDisplayArea, meetingDetails);
//                mddp.loadRecepientsDetail();
//                
//                meetingDetails.update(recR.hashCode(), MeetingDetail.UPDATE_STATUS, ResourceProvider.ACCEPT);
//                mddp.resetAndReload();
//                
//                meetingDetails.update(recR.hashCode(), MeetingDetail.UPDATE_STATUS, ResourceProvider.REJECT);
//                mddp.resetAndReload();
//                
//                meetingDetails.update(recR.hashCode(), MeetingDetail.UPDATE_STATUS, ResourceProvider.UPDATED);
//                mddp.resetAndReload();
//                
//                mddp.updateMeetingChanges(userEmailId, meetingDetails.getStartTime(), meetingDetails.getEndTime(), meetingDetails.getSubject());
//                mddp.updateMeetingToReject(userEmailId);                  
//            }
//            catch(Exception e)
//            {
//                e.printStackTrace();
//                fail("ViewMeetingStatusEnum failed to operate");
//            }
//        }
        
        //View Email EmailFolderNode
        @Test
        public void testEmailFolderNode()
        {
            try
            {
                String inboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, userEmailId);
                EmailFolderNode optionInbox = new EmailFolderNode(ResourceProvider.INBOX);
                optionInbox.setPersistenceFilePath(inboxPath);
                optionInbox.getPersistenceFilePath();
                optionInbox.getFolderName();
                optionInbox.getFolders();
                optionInbox.loadPersistenceFolders();
            }
            catch(Exception e)
            {
                e.printStackTrace();
                fail("testEmailFolderNode failed to operate");
            }
        }
        
        
        //View EmailFolderHierarcyTree
        @Test
        public void testEmailFolderHierarcy()
        {
            try
            {
                EMailFolderHierarchyTree tree = folderHierarchyPanel.getTree();
                
                String inboxPath = ResourceProvider.getRootFolderPath(ResourceProvider.INBOX, userEmailId);
                EmailFolderNode optionInbox = new EmailFolderNode(ResourceProvider.INBOX);
                tree.loadPopMenuOptions(optionInbox);
                tree.addPopUpMenuForDraft();
                tree.addPopUpMenuForInbox();
                tree.addPopUpMenuForOutbox();
                tree.addPopUpMenuForSent();
                tree.addPopUpMenuForTrash();
                tree.loadPersistenceFolders();
                tree.checkIfFolderExist(optionInbox, "newFolder");
                tree.reLoadViews(optionInbox);
                tree.addPopUpMenuForFolders();
                
                
                pers.persistEMail(email, persistenceInboxPath);            
                String dateP = ResourceProvider.converDataFormatToPersistenceFormat(email.getTime());
    
                tree.notifyNewEmailReceived(inboxPath+ ResourceProvider.getFilePathSeperator() + dateP + ".json");
                
                pers.deleteFile(persistenceInboxPath + seperator + emailFileName);
            }
            catch(Exception e)
            {
                e.printStackTrace();
                fail("testEmailFolderNode failed to operate");
            }
        }
        
        // View OptionButtonArea
        @Test
        public void testOptionButtonArea()
        {
            buttonDisplayArea.addLoadTemplateOptions();
            buttonDisplayArea.doesEmailExist(persistenceInboxPath);
            buttonDisplayArea.addTextField("test");
            buttonDisplayArea.addAcceptButton();
            buttonDisplayArea.addEditButton();
            buttonDisplayArea.addRejectButton();
            buttonDisplayArea.notifyObservers("");
            buttonDisplayArea.displayButtonsForNewMeeting();
            buttonDisplayArea.displayButtonsForNewMessage();
            buttonDisplayArea.displayMessageAcceptRejectMeetingUpdate("");
            buttonDisplayArea.displayButtonsToEditOrDelete();
            buttonDisplayArea.displayMessage("test message");
            buttonDisplayArea.displaySearchOptions();
            buttonDisplayArea.getEmailApplicationView();
            
        }
    
}
